#ifndef SERIAL_CLI_H
#define SERIAL_CLI_H
#include <Arduino.h>
#include "dev/network.h"
#include "shared_values.h"
#include "macro.hpp"

void serial_cli_loop() {
    if (!Serial) {
        return; // 如果串口不可用，直接返回
    }
    String command = "";
    if (Serial.available()) {
        command = Serial.readStringUntil('\n');
        command.trim();
        if (command.startsWith("set --ssid ")) {
            String ssid = command.substring(11);
            ssid.trim();
            if (!ssid.isEmpty()) {
                Serial.println("SSID set to: " + ssid);
                global_ssid = strdup(ssid.c_str()); // 更新全局SSID
                wifi_save_to_file(global_ssid, global_password ? global_password : ""); // 保存SSID
            } else {
                Serial.println("Error: SSID cannot be empty.");
            }
        } else if (command.startsWith("set --password ")) {
            String password = command.substring(15);
            password.trim();
            if (!password.isEmpty()) {
                Serial.println("Password set to: " + password);
                global_password = strdup(password.c_str()); // 更新全局密码
                wifi_save_to_file(global_ssid ? global_ssid : "", global_password); // 保存密码
            } else {
                Serial.println("Error: Password cannot be empty.");
            }
        } else if (command == "--restart") {
            Serial.println("Restarting device...");
            delay(1000);
            ESP.restart(); // 重启设备
        } else if (command == "query --wifi") {
            wifi_query_file(); // 查询wifi.txt内容
        }else if (command == "query --ip") {
            Serial.println("IP address: " + WiFi.localIP().toString());
        } else if (command == "reset --wifi") {
            wifi_reset_file(); // 删除wifi.txt文件
        } else if (command == "ls") {
            if (!LittleFS.begin()) {
                Serial.println("[UMEKO][FS] LittleFS初始化失败");
                return;
            }
            Serial.println("[UMEKO][FS] 文件列表:");
            fs::File root = LittleFS.open("/");
            if (!root || !root.isDirectory()) {
                Serial.println("[UMEKO][FS] 无法打开文件系统根目录");
                return;
            }
            fs::File file = root.openNextFile();
            while (file) {
                Serial.printf("  %s (%d bytes)\n", file.name(), file.size());
                file = root.openNextFile();
            }
        } else if (command == "help" || command == "h") {
            Serial.println("Available commands:");
            Serial.println("  set --ssid <SSID>         - Set WiFi SSID");
            Serial.println("  set --password <PWD>      - Set WiFi password");
            Serial.println("  --restart                 - Restart the device");
            Serial.println("  query --wifi              - Query WiFi credentials in wifi.txt");
            Serial.println("  query --ip                - Query IP address");
            Serial.println("  reset --wifi              - Reset WiFi credentials by deleting wifi.txt");
            Serial.println("  stepper --run <FreqSpeed> - Start the stepper motor with specified frequency speed");
            Serial.println("  f <FreqSpeed> - Start the stepper motor with specified frequency speed");
            Serial.println("  query --motor             - Query the current stepper motor frequency");
            Serial.println("  query --macro-status      - Query the status of the macro execution and show loaded commands");
            Serial.println("  query --macro-content     - Query the content of the macro");
            Serial.println("  query --macro-file        - Query the raw content of the macro file");
            Serial.println("  start --macro             - Start executing the macro");
            Serial.println("  stop --macro              - Stop executing the macro");
            Serial.println("  ls                        - List files in the filesystem");
            Serial.println("  help, h                   - Show this help message");
        } else if (command.startsWith("stepper --run ")) {
            String freqSpeedStr = command.substring(13);
            freqSpeedStr.trim();
            double freqSpeed = freqSpeedStr.toDouble();
            stepper->motorSpeed(freqSpeed); // 设置电机速度
            Serial.printf("Stepper running at frequency: %.2f\n", freqSpeed);
        } else if (command.startsWith("f ")) {
            String freqSpeedStr = command.substring(1);
            freqSpeedStr.trim();
            double freqSpeed = freqSpeedStr.toDouble();
            stepper->motorSpeed(freqSpeed); // 设置电机速度
            Serial.printf("Stepper running at frequency: %.2f\n", freqSpeed);
        }else if (command.startsWith("query --motor")) {
            Serial.printf("Stepper running at frequency: %.2f\n", stepper->freqSpeed);
        } else if (command == "query --macro-status") {
            if (macro_running) {
                Serial.printf("[UMEKO][MACRO] 宏正在运行，当前行数: %d\n", macro_position);
            } else {
                Serial.println("[UMEKO][MACRO] 宏未运行");
            }
            show_macro(); // 显示已加载的宏命令
        } else if (command == "query --macro-file") {
            if (!LittleFS.begin()) {
                Serial.println("[UMEKO][FS] LittleFS初始化失败");
                return;
            }
            if (LittleFS.exists(macro_path)) {
                fs::File macroFile = LittleFS.open(macro_path, "r");
                if (!macroFile) {
                    Serial.printf("[UMEKO][FS] 无法打开宏文件 \"%s\"\n", macro_path);
                    return;
                }
                Serial.println("[UMEKO][MACRO] 宏文件内容:");
                while (macroFile.available()) {
                    Serial.println(macroFile.readStringUntil('\n'));
                }
                macroFile.close();
            } else {
                Serial.printf("[UMEKO][FS] 宏文件 \"%s\" 不存在\n", macro_path);
            }
        } else if (command == "start --macro") {
            start_macro();
        } else if (command == "query --macro-content") {
            show_macro();
        }else if (command == "stop --macro") {
            stop_macro();
        } else {
            Serial.println("Unknown command: " + command);
            Serial.println("Type 'help' or 'h' for a list of available commands.");
        }
    }
}

void umeko_welcome(){
    Serial.println("  _    _ __  __ ______ _  __  ____   ____   ___   ");
    Serial.println(" | |  | |  \\/  |  ____| |/ / |  _ \\ / __ \\ / _ \\  ");
    Serial.println(" | |  | | \\  / | |__  | ' /  | |_) | |  | | | | | ");
    Serial.println(" | |  | | |\\/| |  __| |  <   |  _ <| |  | | | | | ");
    Serial.println(" | |__| | |  | | |____| . \\  | |_) | |__| | |_| | ");
    Serial.println("  \\____/|_|  |_|______|_|\\_\\ |____/ \\____/ \\___/  ");
    Serial.println("                Umeko                              ");
    Serial.println("Type 'help' or 'h' for a list of available commands.");
}

#endif // SERIAL_CLI_H